let btn


function s(element) {
    return document.querySelector(element)
}
function es(element) {
    return document.querySelectorAll(element)
}
//生成地图
function createMap(min,max) {
    let createMap = s(".createMap")
    let map = s(".map")
    let x = s(".x")
    let y = s(".y")
    createMap.addEventListener("click", () => {
        if (x.value > max) {
            x.value = max
        }
        if (y.value > max) {
            x.value = max
        }
        if (x.value < min) {
            x.value = min
        }
        if (y.value < min) {
            y.value = min
        }
        let ul = ""
        for (let m = 0; m < x.value; m++) {
            let li = ""
            for(let n = 0; n < y.value; n++) {
                li += `<div class='li' data-x="${m}" data-y="${n}"></div>`
            }
            ul += `<div class="ul">${li}</div>`
        }
        let table = `<div class="table">${ul}</div>`
        map.innerHTML = table
    })
}
//锁定位置
function lockPosition(e){
    let self = e.target
    let t = s(".table")
    if (self.classList.contains("li")) {
        if (btn === 0) {
            let b = s(".b")
            if (b) {
                b.classList.remove("b")
            }
            self.classList.add("b")
        } else if(btn === 1) {
            let e = s(".e")
            if (e) {
                e.classList.remove("e")
            }
            self.classList.add("e")
        } else {
            if (self.classList.contains('w')) {
                self.classList.remove("w")
            } else {
                self.classList.add("w")
            }

        }
    } else {
        alert("设置成功")
        t.removeEventListener("click",lockPosition)
    }
}
//设置起点
function setBegin() {
    let b = s(".begin")
    b.addEventListener("click", () => {
        let t = s(".table")
        if (t) {
            alert("请点击地图方块设置起点")
            btn = 0
            t.addEventListener("click", lockPosition)
        } else {
            alert("请先生成地图")
        }
       
    })
}
//设置终点 
function setEnd() {
    let b = s(".end")
    b.addEventListener("click", () => {
        let t = s(".table")
        if (t) {
            alert("请点击地图方块设置终点")
            btn = 1
            t.addEventListener("click", lockPosition)
        } else {
            alert("请先生成地图")
        }
    })
}
//设置障碍物
function setObstacle() {
    let o = s(".obstacle")
    o.addEventListener('click', () => {
        let t = s(".table")
        if (t) {
            alert("请点击地图方块设置障碍物")
            btn = 2
            t.addEventListener("click", lockPosition)
        } else {
            alert("请先生成地图")
        }
    })
}
//运行
(function (){
    createMap(5,20)
    setBegin()
    setEnd()
    setObstacle()
})()